<template>
  <page-content>
    <space class="my-0">
      <search-form 
        v-if="showSearch"
        :showSearch="showSearch" 
        :popover="false"
        :metaid="metaid"
        :fields="search"
      />
    </space>
    <space class="my-1">
      <option-form 
        :anySelected="!anySelected"
        :pass_delete="pass_delete"
        :pass_force_delete="pass_force_delete"
        :pass_restore="pass_restore"
        :pass_truncate="pass_force_delete"
        :selectedCount="selectedCount"
        :metaid="metaid"
        :selectedRowKeys="selectedRowKeys"
      />
    </space>

    <a-table
      row-key="id"
      :data-source="configs"
      :fixed="this.fixed"
      :scroll="{ x: this.width }"
      bordered
      :pagination="false"
      :row-selection="{
        selectedRowKeys: selectedRowKeys,
        onChange: onSelectChange,
      }"
    >
      <a-table-column 
        title="ID" 
        data-index="id" 
        :width="150"
      />
      <a-table-column 
        title="分类" 
        data-index="category.name" 
        :width="150"
      />
      <a-table-column 
        title="类型" 
        data-index="type_text" 
        :width="150"
      />
      <a-table-column 
        title="名称" 
        data-index="name"
        :width="150"
      />
      <a-table-column 
        title="标识" 
        data-index="slug"
        :width="150"
      />
      <a-table-column 
        title="描述" 
        data-index="desc"
        :width="150"
      />
      <a-table-column 
        title="选项" 
        :width="150"
      >
        <template #default="record">
          <!-- 单选多选 -->
          <span v-if="(record.type==CONFIG_TYPES.MULTIPLE || record.type==CONFIG_TYPES.SINGLE) && record.options" class="ml-1">
            <a-tooltip
              v-if="record.options"
              placement="topLeft"
            >
              <span slot="title" v-if="record.type==CONFIG_TYPES.SINGLE">
                选项来源：
                  <template v-if="record.options.sample == '2'">
                    从数据库导入
                  </template>
                  <template v-else-if="record.options.sample == '3'">
                    从配置项导入
                  </template>
                  <template v-else>
                    手动输入
                  </template>
                  <br/>
                选项设置：{{ record.options.options }}<br/>
                选择形式：
                  <template v-if="record.options.type == 'single_select'">
                    单选下拉
                  </template>
                  <template v-else>
                    单选框
                  </template>
              </span>
              <span v-else-if="record.type==CONFIG_TYPES.MULTIPLE" slot="title">
                选项来源：
                  <template v-if="record.options.sample == '2'">
                    从数据库导入
                  </template>
                  <template v-else-if="record.options.sample == '3'">
                    从配置项导入
                  </template>
                  <template v-else>
                    手动输入
                  </template>
                  <br/>
                选项设置：{{ record.options.options }}<br/>
                选择形式：
                  <template v-if="record.options.type == 'multiple_select'">
                    多选下拉
                  </template>
                  <template v-else-if="record.options.type == 'transfer'">
                    穿梭框
                  </template>
                  <template v-else>
                    多选框
                  </template>
              </span>
              <a-tag color="blue" >{{ record.type }}</a-tag>
            </a-tooltip>
          </span>

          <!-- 树状下拉选择、级联选择 -->
          <span v-else-if="(record.type==CONFIG_TYPES.CASCADER || record.type==CONFIG_TYPES.SELECT_TREE) && record.options" class="ml-1">
            <a-tooltip
              v-if="record.options"
              placement="topLeft"
            >
              <span slot="title">
                选项来源：
                  <template v-if="record.options.sample == '1'">
                    手动输入
                  </template>
                  <template v-else-if="record.options.sample == '2'">
                    从数据库导入
                  </template>
                  <template v-else-if="record.options.sample == '3'">
                    从配置项导入
                  </template>
                  <template v-else-if="record.options.sample == '4'">
                    JSON导入
                  </template>
                  <br/>
                选项设置：{{ record.options.options }}
              </span>
              <a-tag color="blue" >{{ record.type }}</a-tag>
            </a-tooltip>
          </span>

          <!-- 文件上传 -->
          <span v-else-if="record.type==CONFIG_TYPES.FILE && record.options" class="ml-1">
            <a-tooltip
              v-if="record.options"
              placement="topLeft"
            >
              <span slot="title">
                最大上传数：{{record.options.max}}<br/>
                文件类型：{{record.options.ext ? record.options.ext : '不限'}}
              </span>
              <a-tag color="blue" >{{ record.type }}</a-tag>
            </a-tooltip>
          </span>
          <span v-else class="ml-1">
            <a-tag>{{ record.type }}</a-tag>
          </span>
        </template>
      </a-table-column>
      <a-table-column 
        title="默认值" 
        :width="150"
      >
        <template #default="record">
          <div v-if="record.type === CONFIG_TYPES.FILE" style="display: flex; overflow-x: auto">
            <file-preview
              v-for="(item, index) of arrayWrap(record.value)"
              v-if="index<3" 
              :key="index"
              :file="item"
            />
          </div>

          <div v-else-if="record.type==CONFIG_TYPES.MULTIPLE">
            <span
              v-for="(item,index) of record.value" 
              v-if="index<3" 
              :key="item"
            >
              <template v-if="index > 0">
                <a-divider v-if="index < record.value.length+1" type="vertical" />
              </template>
              {{ item }}
            </span>
            <span 
              v-if="record.value.length>3" 
              >...
            </span>
          </div>

          <div v-else-if="record.type=='editor'">
            <doc-preview
              :title="record.label"
              :content="record.value"
              :type="record.type"
            />
          </div>

          <div v-else-if="record.type=='textarea'">
            <doc-preview
              :title="record.label"
              :content="record.value"
              :type="record.type"
            />
          </div>

          <div v-else-if="record.type=='dynamic_input'">
            <doc-preview
              :title="record.label"
              :content="record.value"
              :type="record.type"
            />
          </div>

          <div v-else-if="record.type=='dynamic_textarea'">
            <doc-preview
              :title="record.label"
              :content="record.value"
              :type="record.type"
            />
          </div>

          <div v-else>
            {{ record.value }}
          </div>
        </template>
      </a-table-column>
      <a-table-column 
        title="验证规则" 
        data-index="validation_rules"
        :width="150"
      />
      <a-table-column 
        title="创建时间" 
        data-index="created_at"
        :width="150"
      />
      <a-table-column 
        title="更新时间" 
        data-index="updated_at"
        :width="150"
      />
      <a-table-column 
        title="操作" 
        :width="200" 
        :fixed="this.fixed_right"
      >
        <template #default="record">
          <space>
            <router-link class="text-color" :to="`/configs/${record.id}`">查看</router-link>
            <router-link v-if="!record.deleted_at && pass_put" :to="`/configs/${record.id}/edit`">编辑</router-link>
            <lz-popconfirm v-if="!record.deleted_at && pass_delete" :confirm="destroyConfig(record.id)">
              <a class="error-color" href="javascript:void(0);">删除</a>
            </lz-popconfirm>
            <lz-popconfirm v-if="record.deleted_at && pass_restore" :confirm="restore(record.id)">
              <a class="success-color"  href="javascript:void(0);">恢复</a>
            </lz-popconfirm>
            <lz-popconfirm v-if="record.deleted_at && pass_force_delete" :confirm="forceDelete(record.id)">
              <a class="error-color"  href="javascript:void(0);">彻底删除</a>
            </lz-popconfirm>
          </space>
        </template>
      </a-table-column>
    </a-table>
    <lz-pagination :page="page"/>
  </page-content>
</template>

<script>
import LzPagination from '@c/LzPagination'
import LzPopconfirm from '@c/LzPopconfirm'
import PageContent from '@c/PageContent'
import SearchForm from '@c/SearchForm'
import OptionForm from '@c/OptionForm'
import DocPreview from '@c/DocPreview'
import Space from '@c/Space'
import {
  destroyConfig,
  getConfigs,
} from '@/api/configs'
import {arrayWrap, changeQuery, changeListDefault, changeList, can} from '@/libs/utils'
import { mapConstants } from '@/libs/constants'
import FilePreview from '@c/FilePreview'
import {
  getListField,
  getSearchField,
} from '@/api/field'
import {restore, forceDelete} from '@/api/common'


export default {
  name: 'Index',
  scroll: true,
  components: {
    LzPopconfirm,
    PageContent,
    LzPagination,
    Space,
    SearchForm,
    OptionForm,
    FilePreview,
    DocPreview,
  },
  data() {
    return {
      showSearch:false,
      search: [],
      list: [],
      configs: [],
      page: null,
      width: 1200,
      fixed: false,
      fixed_right: false,
      metaid: this.$route.meta.id,
      selectedRowKeys: [],
    }
  },
  computed: {
    ...mapConstants('CONFIG_TYPES'),
    anySelected() {
      return this.selectedCount > 0
    },
    selectedCount() {
      return this.selectedRowKeys.length
    },
    pass_put() {
      return can('pass-put-configs')
    },
    pass_delete() {
      return can('pass-delete-configs')
    },
    pass_restore() {
      return can('pass-restore')
    },
    pass_force_delete() {
      return can('pass-force-delete')
    },
  },
  methods: {
    arrayWrap,
    onRefresh() {
      this.$router.replace({
        path: this.$route.fullPath,
        query: {
          _refresh: Date.now(),
        },
      })
    },
    restore(id){
      return async () => {
        await restore(this.metaid, id)
        this.onRefresh()
      }
    },
    forceDelete(id){
      return async () => {
        await forceDelete(this.metaid, id)
        this.onRefresh()
      }
    },
    destroyConfig(id) {
      return async () => {
        await destroyConfig(id)
        this.onRefresh()
      }
    },
    async getSearchField(id) {
      const { data } = await getSearchField(id)
      this.search = data
      this.showSearch=true
    },
    async getListField(id) {
      const { data } = await getListField(id)
      this.list = data
    },
    async onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys;
    },
  },
  watch: {
    $route: {
      async handler(newVal) {
        await this.getSearchField(this.$route.meta.id)
        await this.getListField(this.$route.meta.id)
        newVal = changeQuery(newVal)
        const { data: { data, meta } } = await getConfigs(newVal.query)
        this.configs = changeListDefault(data)
        const { list,width } = changeList(this.list, data)
        this.list = list
        this.width = width
        this.page = meta
        if (width > 600) {
          this.fixed_right = 'right'
        }
        this.$scrollResolve()
      },
      immediate: true,
    },
  },
}
</script>
